import os
import threading
import time

import web

from lib import itchat

# Web 应用部分
urls = (
    '/upload/(.*)', 'Upload'
)


class Upload:
    def POST(self, group_name):
        # 获取上传的文件数据
        file_data = web.webapi.data()
        file_name = web.input(file={})
        # 获取文件名
        # 获取文件名 (可选)
        file_extension = os.path.splitext(file_name)[1]  # 获取文件后缀，例如 ".jpg"

        file_path = f"{group_name}_{time.time()}_{file_name}"
        # 保存文件到指定路径
        try:
            with open(file_path, "wb") as f:
                f.write(file_data)
            chat_rooms = itchat.instance.search_chatrooms(name='Test')
            if len(chat_rooms) > 0:
                itchat.instance.send_file(file_path, chat_rooms[0]['UserName'])
            return "File uploaded successfully!"
        except Exception as e:
            return f"Error uploading file: {str(e)}"



app = web.application(urls, globals())


def run_web_server(channel):
    let_chat = channel
    app.run()


# 其他任务部分 (保持不变)
# ...

if __name__ == "__main__":
    # 创建并启动 Web 服务线程
    web_thread = threading.Thread(target=run_web_server)
    web_thread.start()

    # 执行其他任务
    # ...
